package com.example.othree.controller;

import com.alibaba.fastjson.JSON;
import com.example.othree.common.*;
import com.example.othree.entity.User;
import com.example.othree.mapper.UserMapper;
import com.example.othree.service.MailService;
import com.example.othree.util.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@RestController
@CrossOrigin
@RequestMapping("/api")
public class MailController {
    @Autowired
    private MailService mailService;
    @Autowired
    private RedisUtils redisUtils;

    @Resource
    private UserMapper userMapper;

    //发送邮箱验证码
    @GetMapping("/user/email")
    public R emailCode(GetEmailCodeEntity entity) {
        String email = entity.getEmail();
        String username = entity.getUsername();
            User old = userMapper.getUserByEmail(email);
            if(old != null){
                return R.error().message("邮箱不能重复注册");
            } else {
                String emailCode = CodeUtils.getRandomNumber(6);
                //            我们这里做一件事情，那就是最多允许用户在10分钟内发送2次的邮箱验证
                //            60s倒计时后用户可以再发送验证码，但是间隔在10分钟内只能再发送1次
                EmailCodeEntity emailCodeEntity = new EmailCodeEntity(
                        emailCode, username,email,1
                );
                String emailCodeJson = JSON.toJSONString(emailCodeEntity);
                redisUtils.set(RedisTransKey.setEmailKey(username), emailCodeJson,
                        5, TimeUnit.MINUTES
                );
                System.out.println("准备发送");
                mailService.email(email, emailCodeEntity.getEmailCode());
                return R.ok();
            }
    }

}
